package com.bjpowernode.singleton.attack;

import java.io.*;

/**
 * @ClassName Singleton07
 *
 * @Author Cat
 */
public final class SingletonAttack07 implements Serializable {

    private static boolean flag = true;

    static {
        System.out.println(1111111111);
    }

    private SingletonAttack07() {
        if (flag) {
            flag = false;
        } else {
            throw new RuntimeException("反射攻击...");
        }
    }

    // 私有静态内部类中创建并初始化实例对象，private私有化，不能被外部调用
    private static class SingletonInner {
        private static SingletonAttack07 instance = new SingletonAttack07();

        static {
            System.out.println(222222222);
        }
    }

    public static SingletonAttack07 getInstance() {
        return SingletonInner.instance;
    }

    public Object readResolve() {
        return SingletonInner.instance;
    }

    public static void main(String[] args) throws Exception{
        /*SingletonAttack07 instance1 = SingletonAttack07.getInstance();
        System.out.println(instance1);*/

        /*Constructor<SingletonAttack07> constructor = SingletonAttack07.class.getDeclaredConstructor();
        constructor.setAccessible(true);//对私有构造器开放权限

        SingletonAttack07 newInstance1 = constructor.newInstance();
        System.out.println(newInstance1);

        SingletonAttack07 newInstance2 = constructor.newInstance();
        System.out.println(newInstance2);*/


        //序列化
        SingletonAttack07 instance1 = SingletonAttack07.getInstance();
        System.out.println(instance1);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("SerSingleton.obj"));
        oos.writeObject(instance1);
        oos.flush();
        oos.close();

        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("SerSingleton.obj"));
        SingletonAttack07 rs01 = (SingletonAttack07)ois.readObject();
        ois.close();
        System.out.println(rs01);

    }
}